package com.bootdo.acitvity.DDD.interences;

import com.bootdo.acitvity.DDD.application.controller.dto.StockAdjustmentDto;
import com.bootdo.acitvity.DDD.application.controller.dto.StockDistributionDto;
import com.bootdo.acitvity.DDD.domain.CenterBatch;
import com.bootdo.acitvity.DDD.domain.repository.facade.StockRepository;
import com.bootdo.acitvity.utils.R;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author hy
 * @date 2020/5/8
 * @description 库存调整
 */
@Service
@Transactional
public class StockAdjustmentService {

    @Resource
    private StockRepository stockRepository;


    //@Resource
    //private StockRepository2 stockRepository2;


    public String add(StockAdjustmentDto stockDto) {
        String batchId = stockDto.getBatchId();

        //获取聚合跟
        CenterBatch centerBatch = stockRepository.getById(batchId);

        //领域事件
        centerBatch.adjustmentStock(stockDto.getFinStockNum());

        //保存聚合跟
        stockRepository.save(centerBatch);
        return "success";
    }


    public void distributionStock(StockDistributionDto stockDto) {

        //获取聚合跟
        CenterBatch centerBatch = stockRepository.getById(stockDto.getBatchId());

        // 渠道是否有锁定库存
        boolean lockedAlready = centerBatch.isLockedAlready(stockDto.getChannelId());

        if (lockedAlready) {

            //领域事件
            centerBatch.updateStock(stockDto.getStockNum(), stockDto.getFlockStockEndTime());
        } else {
            //领域事件
            centerBatch.lockStock(stockDto.getStockNum(), stockDto.getFlockStockEndTime());
        }
        //保存聚合跟
        stockRepository.save(centerBatch);
    }
}
